<script lang="ts" setup>
import type { FormInstance, DrawerProps } from 'ant-design-vue';
import { $t } from '@vben/locales';
import type { MinishopStoreApply } from './types';
import { onMounted, reactive, ref, watch, computed, toRefs } from 'vue';
import { message } from 'ant-design-vue';
import { removeEmpty, removeNull } from '#/utils/common';
import ImageUpload from '#/components/ImageUpload.vue';
import { useDebounceFn } from '@vueuse/core';
import dayjs, { Dayjs } from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import type { ComponentSetting } from '../../uctoo/component_setting/types.ts';
import { uctoo_minishop_store_apply, uctoo_component_setting } from '#/store';
import { useRepo } from 'pinia-orm';
import { useAxiosRepo } from '@pinia-orm/axios';
import { VbenIcon } from '@vben-core/shadcn-ui';

// 加载 utc 和 timezone 插件
dayjs.extend(utc);
dayjs.extend(timezone);
const loading = ref(false);

const props = defineProps<{
  mode: 'add' | 'edit';
  record: MinishopStoreApply | null;
  visible: boolean;
  componentSettingData: ComponentSetting[];
  ids?:(string[] | number[]);
}>();

// 计算属性判断空值
const isIdsEmpty = computed(() => 
  !props.ids || props.ids.length === 0
);

const emit = defineEmits(['update:visible', 'success']);

const ENTITY_PROXY: { [K in keyof MinishopStoreApply]: null } = {
id: null,
user_id: null,
apply_num: null,
status_msg: null,
status: null,
creator: null,
created_at: null,
updated_at: null,
deleted_at: null,
gender: null,
idcard_image: null,
idcard_no: null,
mobile: null,
realname: null,
skill: null,
user_model: null,
address: null,
age: null,
badly_off: null,
birthday: null,
buddhist_name: null,
career: null,
conversion_time: null,
corporation: null,
education: null,
emergency_contact: null,
emergency_mobile: null,
emergency_relationship: null,
health: null,
idcard_type: null,
job_title: null,
nationality: null,
reason: null,
school: null,
signin_time: null,
signout_time: null,
};
 
// 获取有效字段选项
const getFieldOptions = () => {
  // 排除系统字段
  const EXCLUDED_FIELDS = ['id', 'creator', 'created_at', 'updated_at', 'deleted_at'] as const;
  
  return (Object.keys(ENTITY_PROXY) as Array<keyof MinishopStoreApply>).filter(
    field => !EXCLUDED_FIELDS.includes(field as typeof EXCLUDED_FIELDS[number])
  );
};
const formRef = ref<FormInstance>();


const formState = reactive<Record<keyof MinishopStoreApply, any>>(
  Object.fromEntries(
    getFieldOptions().map(k => [k, '']) // 初始化所有有效字段
  ) as Record<keyof MinishopStoreApply, any>
);
     // 用户选择的表单项，初始化为表单所有项或根据需求预选一些项
    const selectedFormItems = ref<Array<keyof MinishopStoreApply>>(Object.keys(formState) as Array<keyof MinishopStoreApply>);
    const handleFormItemChange = () => {
      console.log('Selected columns:', selectedFormItems.value);
    }; 

/** rules */
const rules = {
 user_id: [{message: $t('page.Required'), required: false}],
 apply_num: [{message: $t('page.Required'), required: false}],
 status_msg: [{message: $t('page.Required'), required: false}],
 status: [{message: $t('page.Required'), required: false}],
 gender: [{message: $t('page.Required'), required: false}],
 idcard_image: [{message: $t('page.Required'), required: false}],
 idcard_no: [{message: $t('page.Required'), required: false}],
 mobile: [{message: $t('page.Required'), required: false}],
 realname: [{message: $t('page.Required'), required: false}],
 skill: [{message: $t('page.Required'), required: false}],
 user_model: [{message: $t('page.Required'), required: false}],
 address: [{message: $t('page.Required'), required: false}],
 age: [{message: $t('page.Required'), required: false}],
 badly_off: [{message: $t('page.Required'), required: false}],
 birthday: [{message: $t('page.Required'), required: false}],
 buddhist_name: [{message: $t('page.Required'), required: false}],
 career: [{message: $t('page.Required'), required: false}],
 conversion_time: [{message: $t('page.Required'), required: false}],
 corporation: [{message: $t('page.Required'), required: false}],
 education: [{message: $t('page.Required'), required: false}],
 emergency_contact: [{message: $t('page.Required'), required: false}],
 emergency_mobile: [{message: $t('page.Required'), required: false}],
 emergency_relationship: [{message: $t('page.Required'), required: false}],
 health: [{message: $t('page.Required'), required: false}],
 idcard_type: [{message: $t('page.Required'), required: false}],
 job_title: [{message: $t('page.Required'), required: false}],
 nationality: [{message: $t('page.Required'), required: false}],
 reason: [{message: $t('page.Required'), required: false}],
 school: [{message: $t('page.Required'), required: false}],
 signin_time: [{message: $t('page.Required'), required: false}],
 signout_time: [{message: $t('page.Required'), required: false}],
};


watch(
  () => props.record,
  (newVal) => {
    if (newVal) {
      Object.assign(formState, newVal);
    } else {
      Object.keys(formState).forEach((key) => {
        formState[key as keyof MinishopStoreApply] = '';
      });
    }

    if(props.componentSettingData[0]){
      selectedFormItems.value = JSON.parse(props.componentSettingData[0].selected_form_column ?? '[]');
    }
  },
  { immediate: true },
);

const handleOk = () => {
  if(isIdsEmpty.value){ //单条数据编辑提交
  console.log(formState);
    interface Formated {
      id?:string,
      user_id?: string,
      apply_num?: number,
      status_msg?: string,
      status?: number,
      gender?: string,
      idcard_image?: string,
      idcard_no?: string,
      mobile?: string,
      realname?: string,
      skill?: string,
      user_model?: string,
      address?: string,
      age?: string,
      badly_off?: string,
      birthday?: Date,
      buddhist_name?: string,
      career?: string,
      conversion_time?: Date,
      corporation?: string,
      education?: string,
      emergency_contact?: string,
      emergency_mobile?: string,
      emergency_relationship?: string,
      health?: string,
      idcard_type?: string,
      job_title?: string,
      nationality?: string,
      reason?: string,
      school?: string,
      signin_time?: Date,
      signout_time?: Date,
     };

    const formatedFormState: Formated = {
      id: formState.id,
      user_id: formState.user_id,
      apply_num: Number(formState.apply_num),
      status_msg: formState.status_msg,
      status: Number(formState.status),
      gender: formState.gender,
      idcard_image: formState.idcard_image,
      idcard_no: formState.idcard_no,
      mobile: formState.mobile,
      realname: formState.realname,
      skill: formState.skill,
      user_model: formState.user_model,
      address: formState.address,
      age: formState.age,
      badly_off: formState.badly_off,
      birthday: formState.birthday,
      buddhist_name: formState.buddhist_name,
      career: formState.career,
      conversion_time: formState.conversion_time,
      corporation: formState.corporation,
      education: formState.education,
      emergency_contact: formState.emergency_contact,
      emergency_mobile: formState.emergency_mobile,
      emergency_relationship: formState.emergency_relationship,
      health: formState.health,
      idcard_type: formState.idcard_type,
      job_title: formState.job_title,
      nationality: formState.nationality,
      reason: formState.reason,
      school: formState.school,
      signin_time: formState.signin_time,
      signout_time: formState.signout_time,
     };

  formRef.value?.validate().then(async () => {
    try {
      if (props.mode === 'add') {
        delete formatedFormState['id'];
        await useAxiosRepo(uctoo_minishop_store_apply).api().adductooMinishopStoreApply(removeEmpty(formatedFormState));
        message.success($t('page.AddSuccess'));
      } else {
        await useAxiosRepo(uctoo_minishop_store_apply).api().edituctooMinishopStoreApply(removeNull(formatedFormState));
          message.success($t('page.EditSuccess'));        
      }
      emit('success');
    } catch {
      message.error($t('page.EditFailed'));
    }
  });
  }else{ //多条数据编辑提交
    handleSubmit();
  }
  
};

const placement = ref<DrawerProps['placement']>('left');
const open = ref<boolean>(false);
const handleCancel = () => {
  emit('update:visible', false);
};

const showDrawer = () => {
  open.value = true;
};

const onClose = () => {
  open.value = false;
};

const onSetting = async () => {
  try {
      if(props.componentSettingData[0]){
        props.componentSettingData[0].selected_form_column = JSON.stringify(selectedFormItems.value);
      }
      await useAxiosRepo(uctoo_component_setting).api().edituctooComponentSetting(removeEmpty(props.componentSettingData[0]));
        message.success($t('page.SaveSuccess'));
    } catch {
      message.error($t('page.EditFailed'));
    }
  open.value = false;
};

// 动态表单项
interface FormField {
  selectedField?: keyof MinishopStoreApply;
  inputValue: string | number;
}

// 响应式表单数据
const formFields = reactive<FormField[]>(
  Array.from({ length: 1 }, () => ({
    selectedField: undefined,
    inputValue: ''
  }))
);

// 添加表单项
const addField = () => {
  formFields.push({ selectedField: undefined, inputValue: '' });
};

const removeField = (index: number) => {
  if (formFields.length > 1) {
    formFields.splice(index, 1);
  }
};

// 处理字段选择变化
const handleFieldChange = (index: number, value: keyof MinishopStoreApply) => {
  // 检查是否已存在相同字段
  const isDuplicate = formFields.some(
    (f, i) => i !== index && f.selectedField === value
  );  
  if (isDuplicate) {
    message.error($t('page.DuplicateSeletedField'));
    return;
  }

  const currentField = formFields[index];
  if (!currentField) return;
  // 清除旧字段的关联状态
  if (currentField.selectedField) {
    delete formState[currentField.selectedField];
  }
  // 更新字段并初始化值
  currentField.selectedField = value;
  currentField.inputValue = isNumberField(value) ? 0 : '';
  // 更新表单状态
  formState[value] = currentField.inputValue;
};

const isNumberField = (field: keyof MinishopStoreApply): boolean => {
  const NUMBER_FIELDS: (keyof MinishopStoreApply)[] = ['apply_num','status',];
  return NUMBER_FIELDS.includes(field);
};

const handleSubmit = async () => {
  // 显式遍历输入组件值并同步到 formFields
  formFields.forEach((field, index) => {
    const inputElement = document.querySelector(`#input-${index}`) as HTMLInputElement;
    if (inputElement) {
      field.inputValue = isNumberField(field.selectedField!) 
        ? Number(inputElement.value) 
        : inputElement.value;
    }
  });
  
    // 转换为目标数据结构
    const formData = formFields.reduce((acc, field) => {
    if (field.selectedField && field.inputValue !== undefined) {
      // 数字字段类型转换
      acc[field.selectedField] = isNumberField(field.selectedField) 
        ? Number(field.inputValue) 
        : field.inputValue;
    }
    return acc;
  }, {} as Record<keyof MinishopStoreApply, any>);
    //ids加入到最终提交数据
  const submitData = {
    ...formData,          // 保留原有字段
     ids: JSON.stringify(props.ids) // 新增序列化后的 ids 字段
  };

  await useAxiosRepo(uctoo_minishop_store_apply).api().edituctooMinishopStoreApply(JSON.parse(JSON.stringify(submitData)));
  message.success($t('page.EditSuccess'));
  emit('success'); 
};

onMounted(() => {
});
</script>

<template>
  <a-modal
    :open="visible"
    :title="mode === 'add' ? $t('page.Add') : $t('page.Edit')"
    @cancel="handleCancel"
    @ok="handleOk"
  >
  <template #footer>
        <a-button type="primary" @click="showDrawer">{{$t('page.Setting')}}</a-button>
        <a-button key="back" @click="handleCancel">{{$t('page.Cancel')}}</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleOk">{{$t('page.Submit')}}</a-button>
      </template> <!-- -->
  <a-drawer :width="500" title="" :placement="placement" :open="open" @close="onClose">
    <template #extra>
      <a-button style="margin-right: 8px" @click="onClose">{{$t('page.Cancel')}}</a-button>
      <a-button type="primary" @click="onSetting">{{$t('page.Submit')}}</a-button>
    </template>
    <a-checkbox-group v-model:value="selectedFormItems" @change="handleFormItemChange">
      <a-checkbox v-for="(value, key) in formState" :key="key" :value="key" >
        {{ $t(`database_column.uctoo_minishop_store_apply.${key}`) }}
      </a-checkbox>
    </a-checkbox-group>
  </a-drawer>

  <a-form v-if="isIdsEmpty" ref="formRef" :model="formState" :rules="rules">
    <a-form-item v-if="selectedFormItems.includes('user_id')" :label="$t('database_column.minishop_store_apply.user_id')" name="user_id">
          <a-input v-model:value="formState.user_id" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('apply_num')" :label="$t('database_column.minishop_store_apply.apply_num')" name="apply_num">
          <a-input v-model:value="formState.apply_num" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('status_msg')" :label="$t('database_column.minishop_store_apply.status_msg')" name="status_msg">
          <a-input v-model:value="formState.status_msg" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('status')" :label="$t('database_column.minishop_store_apply.status')" name="status">
          <a-input v-model:value="formState.status" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('gender')" :label="$t('database_column.minishop_store_apply.gender')" name="gender">
          <a-input v-model:value="formState.gender" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('idcard_image')" :label="$t('database_column.minishop_store_apply.idcard_image')" name="idcard_image">
            <ImageUpload v-model="formState.idcard_image" :max-count="20" :upload-text="$t('page.image_upload')" />
          </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('idcard_no')" :label="$t('database_column.minishop_store_apply.idcard_no')" name="idcard_no">
          <a-input v-model:value="formState.idcard_no" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('mobile')" :label="$t('database_column.minishop_store_apply.mobile')" name="mobile">
          <a-input v-model:value="formState.mobile" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('realname')" :label="$t('database_column.minishop_store_apply.realname')" name="realname">
          <a-input v-model:value="formState.realname" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('skill')" :label="$t('database_column.minishop_store_apply.skill')" name="skill">
          <a-input v-model:value="formState.skill" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('user_model')" :label="$t('database_column.minishop_store_apply.user_model')" name="user_model">
          <a-input v-model:value="formState.user_model" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('address')" :label="$t('database_column.minishop_store_apply.address')" name="address">
          <a-input v-model:value="formState.address" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('age')" :label="$t('database_column.minishop_store_apply.age')" name="age">
          <a-input v-model:value="formState.age" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('badly_off')" :label="$t('database_column.minishop_store_apply.badly_off')" name="badly_off">
          <a-input v-model:value="formState.badly_off" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('birthday')" :label="$t('database_column.minishop_store_apply.birthday')" name="birthday">
          <a-input v-model:value="formState.birthday" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('buddhist_name')" :label="$t('database_column.minishop_store_apply.buddhist_name')" name="buddhist_name">
          <a-input v-model:value="formState.buddhist_name" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('career')" :label="$t('database_column.minishop_store_apply.career')" name="career">
          <a-input v-model:value="formState.career" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('conversion_time')" :label="$t('database_column.minishop_store_apply.conversion_time')" name="conversion_time">
          <a-input v-model:value="formState.conversion_time" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('corporation')" :label="$t('database_column.minishop_store_apply.corporation')" name="corporation">
          <a-input v-model:value="formState.corporation" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('education')" :label="$t('database_column.minishop_store_apply.education')" name="education">
          <a-input v-model:value="formState.education" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('emergency_contact')" :label="$t('database_column.minishop_store_apply.emergency_contact')" name="emergency_contact">
          <a-input v-model:value="formState.emergency_contact" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('emergency_mobile')" :label="$t('database_column.minishop_store_apply.emergency_mobile')" name="emergency_mobile">
          <a-input v-model:value="formState.emergency_mobile" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('emergency_relationship')" :label="$t('database_column.minishop_store_apply.emergency_relationship')" name="emergency_relationship">
          <a-input v-model:value="formState.emergency_relationship" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('health')" :label="$t('database_column.minishop_store_apply.health')" name="health">
          <a-input v-model:value="formState.health" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('idcard_type')" :label="$t('database_column.minishop_store_apply.idcard_type')" name="idcard_type">
          <a-input v-model:value="formState.idcard_type" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('job_title')" :label="$t('database_column.minishop_store_apply.job_title')" name="job_title">
          <a-input v-model:value="formState.job_title" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('nationality')" :label="$t('database_column.minishop_store_apply.nationality')" name="nationality">
          <a-input v-model:value="formState.nationality" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('reason')" :label="$t('database_column.minishop_store_apply.reason')" name="reason">
          <a-input v-model:value="formState.reason" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('school')" :label="$t('database_column.minishop_store_apply.school')" name="school">
          <a-input v-model:value="formState.school" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('signin_time')" :label="$t('database_column.minishop_store_apply.signin_time')" name="signin_time">
          <a-input v-model:value="formState.signin_time" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('signout_time')" :label="$t('database_column.minishop_store_apply.signout_time')" name="signout_time">
          <a-input v-model:value="formState.signout_time" />
        </a-form-item>
</a-form>

<!-- edit multi row -->
  <a-form v-else class="dynamic-form" ref="formRef" :model="formState">
    <a-form-item v-for="(field, index) in formFields" :key="index" class="form-row">
      <!-- 字段选择器 -->
      <a-space>
      <a-select 
        v-model="field.selectedField"
        :placeholder="$t('page.SelectField')"
        @change="(value:any) => handleFieldChange(index, value)"
        style="width: 160px"
      >
        <a-option 
          v-for="opt in getFieldOptions()" 
          :key="opt" 
          :value="opt"
        >
          {{ opt }}
        </a-option>
      </a-select>

      <!-- 动态输入组件：直接绑定到 field -->
      <a-input
        :id="`input-${index}`"
        v-if="field.selectedField && isNumberField(field.selectedField)"
        v-model.number="field.inputValue"
        type="number"
      />
      <a-input
        :id="`input-${index}`"
        v-else
        v-model="field.inputValue"
      />
      <a-button 
        v-if="index > 0" 
        @click="removeField(index)"
        type="danger"
      >
      <template #icon><VbenIcon icon="ant-design:minus-circle-outlined" /></template>
      </a-button>
      </a-space>
    </a-form-item>
  
    <a-button @click="addField" type="danger">
      <template #icon><VbenIcon icon="ant-design:plus-circle-outlined" /></template>
    </a-button>
  </a-form>
  </a-modal>
</template>
